<?php

namespace Common\Model;
use Think\Model;

class AreaModel extends Model{

    protected $_validate = array(
        array( 'region_name', 'require', '名称必须填写' ),
    );
    
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    /**
     * 新增或更新
     * 
     * @return boolean fasle 失败 ， int 成功 返回完整的数据
     */
    public function update($data, $regionList)
    {
        $data = $this->create($data);
        if (empty($data)) {
            return false;
        }
        if (empty($data['area_id'])) {
            try {
                $this->startTrans();
                $id = $this->add();
                $regionRela = array();
                $regionIDS = array();
                foreach ($regionList as $val){
                    $regionRela[] = array('area_id' => $id, 'region_id' => $val );
                    $regionIDS[] = $val;
                }
                M('AreaRegion')->where(array('region_id' => array('in' , $regionIDS)))->delete();
                $rela = M('AreaRegion')->addAll($regionRela);
                $result = $this->commit();
            } catch (\Exception $e) {
                $this->error = '新增出错';
                $this->rollback();
                return false;
            }
        } else {
            try {
                $this->startTrans();
                $result = $this->where(array( 'area_id' => $data['area_id'] ))->save($data);
                $regionRela = array();
                $regionIDS = array();
                foreach ($regionList as $val){
                    $regionRela[] = array('area_id' => $data['area_id'], 'region_id' => $val );
                    $regionIDS[] = $val;
                }
                $del = M('AreaRegion')->where(array( 'area_id' => $data['area_id'] ))->delete();
                M('AreaRegion')->where(array('region_id' => array('in' , $regionIDS)))->delete();
                $rela = M('AreaRegion')->addAll($regionRela);
                $result = $this->commit();
            } catch (\Exception $e) {
                $this->error = '更新出错';
                $this->rollback();
                return false;
            }
        }
        return $result;
    }

}
